package com.winter.service;

import com.google.common.base.Strings;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winter.mapper.DictEntryMapper;
import com.winter.mapper.FinContentLikeInfoMapper;
import com.winter.mapper.FinFavInfoMapper;
import com.winter.mapper.FinUnderlineMapper;
import com.winter.mapper.IcompanyCardMapper;
import com.winter.mapper.UserInfoMapper;
import com.winter.model.DictEntry;
import com.winter.model.FinContentLikeInfo;
import com.winter.model.FinCpaper;
import com.winter.model.FinUnderline;
import com.winter.model.IcompanyCard;
import com.winter.model.UserInfo;
import com.winter.model.vo.check.CheckParam;
import com.winter.model.vo.request.OfflineRequestVo;
import com.winter.util.Constants;
import com.winter.util.Result;
import com.winter.util.ResultCode;

@Service
@Transactional
public class FinUnderlineService {

    @Autowired
    private FinUnderlineMapper finUnderlineMapper;

    /**
     * 点赞
     */
    @Autowired
    private FinContentLikeInfoMapper finContentLikeInfoMapper;

    /**
     * 收藏
     */
    @Autowired
    private FinFavInfoMapper finFavInfoMapper;

    /**
     * 字典
     */
    @Autowired
    private DictEntryMapper dictEntryMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IcompanyCardMapper icompanyCardMapper;

    /**
     * 查询报价平台线下List信息
     */
    public Result finUList(Integer pageNumber, Integer pageSize, String direct, String fund_mode, String termUnit, String rateUnit, String userNo, String sortName, String sort, String key) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }

        PageHelper.startPage(pageNumber, pageSize, false);
        List<FinUnderline> finUnderlines = finUnderlineMapper.finUlist(direct, fund_mode, termUnit, rateUnit, sortName, sort, key);
        finUnderlines.forEach(f -> {
            String photoPath = null;
            String photoType = f.getPhotoType();
            if (!Strings.isNullOrEmpty(photoType)) {
                if (photoType.equals("0")) {
                    // 获取创建人头像
                    String createUser = f.getCreateUser();
                    UserInfo userInfo = userInfoMapper.selectByUserNo(createUser);
                    if (userInfo != null) {
                        String custImgUrl = userInfo.getCustImgUrl();
                        if (!Strings.isNullOrEmpty(custImgUrl)) {
                            f.setAvatar(userInfo.getCustImgUrl());
                        }
                    } else {
                        //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
                        //(int)(1+Math.random()*(10-1+1))
                        int verycode = (int) (1 + Math.random() * (70 - 1 + 1));
                        photoPath = "/p2p/images/imgthumbs/headimg_" + verycode + ".jpg";
                        f.setAvatar(photoPath);
                    }
                } else {
                    //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
                    //(int)(1+Math.random()*(10-1+1))
                    int verycode = (int) (1 + Math.random() * (70 - 1 + 1));
                    photoPath = "/p2p/images/imgthumbs/headimg_" + verycode + ".jpg";
                    f.setAvatar(photoPath);
                }
            }


            f.setIsCollect("0");
            f.setIsLike("0");
            //获取字典名称
            getTypeName(f);
            // 获取是否点赞或者收藏
            if (!Strings.isNullOrEmpty(userNo)) {
                getIsLikeOrCollect(userNo, f);
            }
        });
        PageInfo<FinUnderline> pageInfo = new PageInfo<>(finUnderlines);
        return Result.success(pageInfo);
    }

    /**
     * 获取字典实体名称
     */
    public void getTypeName(FinUnderline finUnderline) {
        if (!Strings.isNullOrEmpty(finUnderline.getDirect())) {
            // 方向
            DictEntry dictEntry = get("DC_MONEY_DIRECTION", finUnderline.getDirect());
            if (dictEntry != null) {
                finUnderline.setDirect(dictEntry.getDictname());
            }
        }

        // 种类
        if (!Strings.isNullOrEmpty(finUnderline.getFundMode())) {
            DictEntry dictEntry = get("DC_OFFLINE_TYPE", finUnderline.getFundMode());
            if (dictEntry != null) {
                finUnderline.setFundMode(dictEntry.getDictname());
            }
        }
        // 币种
        if (!Strings.isNullOrEmpty(finUnderline.getCcy())) {
            DictEntry dictEntry = get("DC_CURRENCY_TYPE", finUnderline.getCcy());
            if (dictEntry != null) {
                finUnderline.setCcy(dictEntry.getDictname());
            }
        }
    }

    /**
     * 获取字典实体
     */
    public DictEntry get(String type, String chiType) {
        DictEntry dictEntry = dictEntryMapper.get(type, chiType);
        return dictEntry;
    }


    /**
     * 获取是否收藏和点赞
     */
    private void getIsLikeOrCollect(String userNo, FinUnderline f) {
        List<FinContentLikeInfo> isLike = finContentLikeInfoMapper.getIsLike(f.getId(), "1", "2", userNo);
        if (isLike.size() > 0) {
            f.setIsLike("1");
        } else {
            f.setIsLike("0");
        }
        // 获取是否收藏
        Long i = finFavInfoMapper.get(f.getId(), "1", 2, userNo);
        if (i > 0) {
            f.setIsCollect("1");
        } else {
            f.setIsCollect("0");
        }
    }

    /**
     * 通过id查询报价平台线下信息
     */
    public Result getFinUnderlineId(Long id, String userNo) {
        FinUnderline fu = finUnderlineMapper.selectByPrimaryKey(id);
        // 获取字典名称
        getTypeName(fu);
        //获取是否点赞或者收藏
        if (!Strings.isNullOrEmpty(userNo)) {
            getIsLikeOrCollect(userNo, fu);
        }
        return Result.success(fu);
    }

    /**
     * 新增报价平台线下信息
     */
    @Transactional
    public Result insertFinUnderline(OfflineRequestVo requestVo) {
        if (Strings.isNullOrEmpty(requestVo.getUserNo())) {
            return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
        }
        String check = CheckParam.checkOffline(requestVo);
        if (!Strings.isNullOrEmpty(check)) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, check);
        }
        // 获取用户设置的期限列表
        if (requestVo.getDeadline()
                     .size() > 0) {
            requestVo.getDeadline()
                     .forEach(f -> {
                         FinUnderline finUnderline = new FinUnderline();
                         finUnderline.setAuditing("0");
                         finUnderline.setUpdatetime(new Date());
                         finUnderline.setCreatetime(new Date());
                         finUnderline.setIsvalid("1");
                         finUnderline.setPhotoType("0");
                         finUnderline.setStas("3");
                         finUnderline.setCreateUser(requestVo.getUserNo());
                         finUnderline.setUpdateUser(requestVo.getUserNo());
                         finUnderline.setDirect(requestVo.getDirect());
                         finUnderline.setCcy(requestVo.getCcy());
                         finUnderline.setFundMode(requestVo.getFundMode());
                         finUnderline.setContact(requestVo.getContact());
                         finUnderline.setContent(requestVo.getContent());
                         finUnderline.setRemark(requestVo.getContent());
                         finUnderline.setTermEnd(f.getTermEnd());
                         finUnderline.setTermBeg(f.getTermBeg());
                         finUnderline.setTermUnit(f.getTermUnit());
                         finUnderline.setDeadlineFlag(f.getDeadlineFlag());
                         finUnderline.setRateEnd(f.getRateEnd());
                         finUnderline.setRateUnit(f.getRateUnit());
                         finUnderline.setRateBeg(f.getRateBeg());
                         finUnderline.setMonEnd(f.getMonEnd());
                         finUnderline.setMonUnit(f.getMonUnit());
                         finUnderline.setCommentCount(new BigDecimal("0"));
                         finUnderline.setFavCount(new BigDecimal("0"));
                         finUnderline.setLikeCount(new BigDecimal("0"));
                         finUnderline.setCommentFlag("1");
                         finUnderline.setLikeFlag("1");
                         finUnderline.setReplayFlag("1");
                         finUnderline.setPhotoType("0");
                         finUnderline.setInfoSrc("0");
                         UserInfo userInfo = userInfoMapper.selectByUserNo(requestVo.getUserNo());
                         String orgNo = userInfo.getOrgNo();
                         IcompanyCard icompanyCard = icompanyCardMapper.selectByPrimaryKey(Long.valueOf(orgNo));
                         // 公司信息
                         finUnderline.setUserName(userInfo.getUserName());
                         finUnderline.setUserCom(icompanyCard.getCompanyName());
                         finUnderline.setUserDepart(userInfo.getDepart());
                         finUnderline.setUserPost(userInfo.getPost());
                         finUnderline.setUserEmail(userInfo.getOrgEmail());
                         finUnderline.setUserQq(userInfo.getQq() + "");
                         finUnderline.setUserWx(userInfo.getWxNo());
                         finUnderline.setTopTime(new Date());
                         finUnderlineMapper.insertSelective(finUnderline);
                     });
            return Result.success("添加成功");
        }
        return Result.failure(ResultCode.PARAM_IS_BLANK, "添加失败");
    }

    /**
     * 修改线下
     */
    public Result updateFinUnderline(FinUnderline finUnderline) {
        if (finUnderline != null) {
            if (finUnderline.getId() == null) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "主键id不能为空");
            }
            if (Strings.isNullOrEmpty(finUnderline.getDirect())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择方向");
            }
            if (Strings.isNullOrEmpty(finUnderline.getFundMode())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择种类");
            }
            if (Strings.isNullOrEmpty(finUnderline.getCcy())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择币种");
            }
            if (Strings.isNullOrEmpty(finUnderline.getContact())) {
                return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入联系方式");
            }
            finUnderline.setUpdatetime(new Date());
            finUnderlineMapper.updateByPrimaryKeySelective(finUnderline);
            return Result.success("修改成功");
        } else {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "参数列表为空");
        }
    }
}
